<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Prop extends Base
{
    protected $table = 'prop';
    protected $primaryKey = 'prop_id';
    protected $redisKeyPro = 'CACHE:PROP:';
    protected $propLogTable = 'prop_log';
    protected $userPackTable = 'prop_user_pack';

    protected $userPackPrimaryKey = 'user_pack_id';
    public $glory_prop_id = 302;

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 道具-列表分页
     *
     * @param array $condition 条件
     * @param int $page 页数 默认0
     * @param int $limit 条数 默认10
     * @return array
     * */
    public function getPropList($condition = [], $page = 0, $limit = 10)
    {
        $db = DB::table($this->table)->where($condition);

        // 总条数
        $totalCount = $db->count($this->primaryKey);

        // 查询数据
        $list = $db->offset($page * $limit)->limit($limit)->get()->toArray();
        $list = self::objToArray($list);

        return $this->checkPageData($page, $limit, $totalCount, $list);
    }

    /**
     * 道具-根据道具ID获取
     *
     * @param int $propId 道具ID
     * @return array
     * */
    public function getPropById($propId)
    {
        $db = DB::table($this->table);
        $getData = $db->where([$this->primaryKey => $propId])->first();
        return self::objToArray($getData);
    }

    /**
     * 道具-创建/更新/删除
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $propId 道具ID
     * @return bool
     * */
    public function CUDProp($data = [], $type = 'insert', $propId = 0)
    {
        switch ($type) {
            case 'insert':
                $data['created_at'] = time();
                $ret = DB::table($this->table)->insertGetId($data);
                break;
            case 'update':
                //删除缓存实时更新
                Redis::del($this->redisKeyPro.$propId);

                $ret = DB::table($this->table)->where([$this->primaryKey => $propId])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->table)->where([$this->primaryKey => $propId])->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /**
     * 道具-根据道具ID获取
     *
     * @param array $propIdArray 道具ID组
     * @return array
     * */
    public function getPropByIds($propIdArray)
    {
        $data = [];

        do {
            $getData = Redis::MGET(array_map(function ($propConfigId) {
                return $this->redisKeyPro . $propConfigId;
            }, $propIdArray));

            foreach ($getData as $key => $value) {
                if (empty($value)) {
                    unset($getData[$key]);
                    continue;
                }
                $data[] = json_decode($value, true);
                unset($propIdArray[$key]);
            }
            if (empty($propIdArray)) {
                break;
            }

            $db = DB::table($this->table);
            $getData = $db->whereIn($this->primaryKey, $propIdArray)->get()->toArray();
            $getData = self::objToArray($getData);
            foreach ($getData as $key => $value) {
                if (!empty($value['data_image'])) {
                    $value['data_image'] = build_image($value['data_image']);
                }
                $data[] = $value;
                Redis::setex($this->redisKeyPro . $value[$this->primaryKey], 3600, json_encode($value, JSON_UNESCAPED_UNICODE));
            }

        } while (false);

        return $data;
    }

    /**
     * @param $user_id
     * @param $prop_id
     * @param int $suid
     * @param int $num
     * @param int $type 25一元充值任务领取 26赠送 27周年活动 40图鉴-成就 50打神兽活动 55陪伴型小屋(满30分钟发奖励) 60图鉴月守护积分榜前三 70用户关系购买道具
     * @return bool
     */
    public function grantProp($user_id, $prop_id, $suid = 0, $num = 1, $type = 1)
    {
        // 创建发放日志
        $propLogData = [
            "user_id" => $user_id,
            "prop_id" => $prop_id,
            "suid" => $suid,
            "type" => $type,
            "change" => $num,
            'created_at' => time()
        ];

        $result['prop_log_id'] = DB::table($this->propLogTable)->insertGetId($propLogData);
        if (!$result['prop_log_id']) {
            return false;
        }

        // 检测用户背包道具是否存在
        $userPackData = [
            'user_id' => $user_id,
            'prop_id' => $prop_id,
            'num' => $num,
        ];

        $inputType = "insert";
        $checkUserPack = DB::table($this->userPackTable)->where(['user_id' => $user_id, 'prop_id' => $prop_id])->first();
        $checkUserPack = self::objToArray($checkUserPack);
        if (!empty($checkUserPack)) {
            $inputType = 'increment';
            $userPackData['user_pack_id'] = $checkUserPack['user_pack_id'];
        }

        // 创建/更新 用户背包
        $ret = $this->updateOrInsertUserPack($userPackData, $inputType);
        if (!$ret) {
            return false;
        }

        return $result;

    }


    /**
     * 获取道具的数量
     * @param $userId
     * @param $propId
     * @return int
     */
    public function getUserPropNum($userId, $propId)
    {
        $result = DB::table($this->userPackTable)
            ->where('user_id', '=', $userId)
            ->where('prop_id', '=', $propId)
            ->first(['num']);
        if (empty($result)){
            return 0;
        }
        $result = self::objToArray($result);
        return intval($result['num']);
    }

    /**
     * 用户背包-创建/更新
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新，increment=累加，decrement=减少
     * @return bool
     * */
    public function updateOrInsertUserPack($data, $type = 'insert')
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->userPackTable)->insertGetId([
                    'user_id' => $data['user_id'],
                    'prop_id' => $data['prop_id'],
                    'num' => $data['num'],
                    'created_at' => time(),
                ]);
                break;
            case 'update':
                $ret = DB::table($this->userPackTable)->where([$this->userPackPrimaryKey => $data[$this->userPackPrimaryKey]])->update(['num' => $data['num']]);
                break;
            case 'increment':
                $ret = DB::table($this->userPackTable)->where([$this->userPackPrimaryKey => $data[$this->userPackPrimaryKey]])->increment('num', $data['num']);
                break;
            case 'decrement':
                $ret = DB::table($this->userPackTable)->where([$this->userPackPrimaryKey => $data[$this->userPackPrimaryKey]])->decrement('num', $data['num']);
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }


}
